#!/usr/bin/perl

use strict;
use Data::Dumper;
use FileHandle;

sub parseEnum($)
{
   my $fh = shift;

   my $enum = {};
   my $last_val = 0;

   while(<$fh>) {

      s/^\s*(.*)\s*$/\1/;

      next if (/^$/);   #empty line
      next if (/^[{#;]/); #preprocess or start of block

      return $enum if (/^}/); #end of block

      my ($key, $val) = split "=";
      $key =~ s/,\s*//;
      if ($val) {
         $last_val = $val;
      }
      else {
         $last_val++;
         $val = $last_val;
      }
      $enum->{$key} = $val;
   }

   return undef; #it should be syntax error here
}

sub readEnums(@)
{
   my %enums = ();

   my $fh = FileHandle->new;

   for my $cpp_file (@_) {
      $fh->open("cpp $cpp_file|") || die "Cannot open $cpp_file\n";

      while(<$fh>) {
         if (/^\s*enum\s*([^\s]+)/) {
            my $name = $1;
            my $enum = parseEnum($fh);
            $enums{$name} = $enum;
         }
      }

     $fh->close;  
   }

   return \%enums;   
}

sub printEnum($)
{
   my $enums_ref = shift;
   
   print "#!/usr/bin/perl\n\n";
   
   for my $enum_name (keys %{$enums_ref})
   {
      print "package $enum_name;\n\n"
                . "use strict;\n\n"
                . "use constant\n"
                . "{\n";
                        
          my $enum = $enums_ref->{$enum_name};
          for my $key (sort {$enum->{$a} <=> $enum->{$b}} keys %{$enum}) {
             my $val = $enum->{$key};
                 print "\t$key\t=> $val,\n";
          }
          print "};\n\n";
   }
   print "1;\n";
}

my $enums = readEnums(@ARGV);
#print "DEBUG:\n" . Dumper($enums) . "\n";

printEnum($enums);


